package com.bilibili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bilibili.dao.FileMapper;
import com.bilibili.domain.entity.File;
import com.bilibili.service.FileService;
import com.bilibili.utils.FastDFSUtil;
import com.bilibili.utils.MD5Util;
import io.netty.util.internal.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

/**
* @author www
* @description 针对表【t_file(文件表)】的数据库操作Service实现
* @createDate 2024-06-15 19:35:51
*/
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File>
    implements FileService {

    @Resource
    private FileMapper fileMapper;

    @Resource
    private FastDFSUtil fastDFSUtil;

    LambdaQueryWrapper<File> wrapper = new LambdaQueryWrapper<>();

    /**
     * 对文件进行md5加密，获取唯一标识
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public String getFileMd5(MultipartFile file) throws Exception {
        return MD5Util.getFileMD5(file);
    }

    @Transactional
    @Override
    public String uploadFileBySlices(MultipartFile slice, String fileMD5, Integer sliceNo, Integer totalSliceNo) throws Exception {
        wrapper.eq(File::getMd5,fileMD5);
        //通过md5获取文件
        File dbFileMD5 = fileMapper.selectOne(wrapper);
        //如果文件存在，进行秒传
        if(dbFileMD5 != null){
            return dbFileMD5.getUrl();
        }
        //不存在，插入数据库
        String url = fastDFSUtil.uploadFileBySlices(slice, fileMD5, sliceNo, totalSliceNo);
        if(!StringUtil.isNullOrEmpty(url)){
            dbFileMD5 = new File();
            dbFileMD5.setCreateTime(new Date());
            dbFileMD5.setMd5(fileMD5);
            dbFileMD5.setUrl(url);
            dbFileMD5.setType(fastDFSUtil.getFileType(slice));
            fileMapper.insert(dbFileMD5);
        }
        return url;
    }
}




